package org.mat.ipaas.ucenter.service.modules.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.mat.framework.lang.dto.MatApiResponse;
import org.mat.ipaas.ucenter.biz.common.api.dto.DataLog;
import org.mat.ipaas.ucenter.biz.common.constant.CommonConstant;
import org.mat.ipaas.ucenter.biz.common.system.api.ISysBaseAPI;
import org.mat.ipaas.ucenter.biz.common.system.query.QueryGenerator;
import org.mat.ipaas.ucenter.biz.modules.system.entity.SysComment;
import org.mat.ipaas.ucenter.biz.modules.system.service.ISysCommentService;
import org.mat.ipaas.ucenter.biz.modules.system.vo.SysCommentFileVo;
import org.mat.ipaas.ucenter.biz.modules.system.vo.SysCommentVO;
import org.mat.ipaas.ucenter.service.api.system.SysCommentRestAPI;
import org.mat.ipaas.ucenter.service.dto.system.entity.SysCommentDTO;
import org.mat.ipaas.ucenter.service.dto.system.vo.LoginUserDTO;
import org.mat.ipaas.ucenter.service.dto.system.vo.SysCommentFileVoDTO;
import org.mat.ipaas.ucenter.service.dto.system.vo.SysCommentVODTO;
import org.mat.ipaas.ucenter.service.modules.MatController;
import org.mat.ipaas.ucenter.service.modules.SessionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 系统评论回复表
 */
@Api(tags = "系统评论回复表")
@RestController
@RequestMapping("/sys/comment")
@Slf4j
public class SysCommentController extends MatController<SysComment, ISysCommentService> implements SysCommentRestAPI {

    @Autowired
    private SessionService sessionService;

    @Autowired
    private ISysCommentService sysCommentService;

    @Autowired
    private ISysBaseAPI sysBaseAPI;


    /**
     * 在线预览文件地址
     */
    @Value("${mat.file-view-domain}/onlinePreview")
    private String onlinePreviewDomain;

    /**
     * 查询评论+文件
     *
     * @param sysCommentDTO
     * @return
     */
    @ApiOperation(value = "系统评论回复表-列表查询", notes = "系统评论回复表-列表查询")
    @GetMapping(value = "/listByForm")
    public MatApiResponse<IPage<SysCommentVODTO>> queryListByForm(SysCommentDTO sysCommentDTO) {
        SysComment sysComment = toSysComment(sysCommentDTO);

        List<SysCommentVO> list = sysCommentService.queryFormCommentInfo(sysComment);
        IPage<SysCommentVO> pageList = new Page();
        pageList.setRecords(list);
        return MatApiResponse.success(toSysCommentVODTOPage(pageList));
    }

    /**
     * 查询文件
     *
     * @param sysCommentDTO
     * @return
     */
    @ApiOperation(value = "系统评论回复表-列表查询", notes = "系统评论回复表-列表查询")
    @GetMapping(value = "/fileList")
    public MatApiResponse<IPage<SysCommentFileVoDTO>> queryFileList(SysCommentDTO sysCommentDTO) {
        SysComment sysComment = toSysComment(sysCommentDTO);
        List<SysCommentFileVo> list = sysCommentService.queryFormFileList(sysComment.getTableName(), sysComment.getTableDataId());
        IPage<SysCommentFileVo> pageList = new Page();
        pageList.setRecords(list);
        return MatApiResponse.success(toSysCommentFileVoDTOPage(pageList));
    }

    @ApiOperation(value = "系统评论表-添加文本", notes = "系统评论表-添加文本")
    @PostMapping(value = "/addText")
    public MatApiResponse<String> addText(@RequestBody SysCommentDTO sysCommentDTO) {
        SysComment sysComment = toSysComment(sysCommentDTO);

        String commentId = sysCommentService.saveOne(sysComment);
        return MatApiResponse.success(commentId);
    }

    @ApiOperation(value = "系统评论表-添加文件", notes = "系统评论表-添加文件")
    @PostMapping(value = "/addFile")
    public MatApiResponse<String> addFile(HttpServletRequest request) {
        try {
            sysCommentService.saveOneFileComment(request);
            return MatApiResponse.success("success");
        } catch (Exception e) {
            log.error("评论文件上传失败：{}", e.getMessage());
            return MatApiResponse.fail("操作失败," + e.getMessage());
        }
    }

    @ApiOperation(value = "系统评论回复表-通过id删除", notes = "系统评论回复表-通过id删除")
    @DeleteMapping(value = "/deleteOne")
    public MatApiResponse<String> deleteOne(@RequestParam(name = "id", required = true) String id) {
        SysComment comment = sysCommentService.getById(id);
        if (comment == null) {
            return MatApiResponse.fail("该评论已被删除！");
        }
        LoginUserDTO sysUser = sessionService.getLoginUser();
        String username = sysUser.getUsername();
        String admin = "admin";
        //除了admin外 其他人只能删除自己的评论
        if ((!admin.equals(username)) && !username.equals(comment.getCreateBy())) {
            return MatApiResponse.fail("只能删除自己的评论！");
        }
        sysCommentService.deleteOne(id);
        //删除评论添加日志
        String logContent = "删除了评论， " + comment.getCommentContent();
        DataLog dataLog = new DataLog(comment.getTableName(), comment.getTableDataId(), logContent, CommonConstant.DATA_LOG_TYPE_COMMENT);
        sysBaseAPI.saveDataLog(dataLog);
        return MatApiResponse.success("删除成功!");
    }


    /**
     * 获取文件预览的地址
     *
     * @return
     */
    @GetMapping(value = "/getFileViewDomain")
    public MatApiResponse<String> getFileViewDomain() {
        return MatApiResponse.success(onlinePreviewDomain);
    }


    /**
     * 分页列表查询
     *
     * @param sysCommentDTO
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "系统评论回复表-分页列表查询")
    @ApiOperation(value = "系统评论回复表-分页列表查询", notes = "系统评论回复表-分页列表查询")
    @GetMapping(value = "/list")
    public MatApiResponse<IPage<SysCommentDTO>> queryPageList(SysCommentDTO sysCommentDTO,
                                                              @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                              @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                              HttpServletRequest req) {
        SysComment sysComment = toSysComment(sysCommentDTO);

        QueryWrapper<SysComment> queryWrapper = QueryGenerator.initQueryWrapper(sysComment, req.getParameterMap());
        Page<SysComment> page = new Page<SysComment>(pageNo, pageSize);
        IPage<SysComment> pageList = sysCommentService.page(page, queryWrapper);
        return MatApiResponse.success(tpSysCommentDTOPage(pageList));
    }


    /**
     * 添加
     *
     * @param sysCommentDTO
     * @return
     */
    @ApiOperation(value = "系统评论回复表-添加", notes = "系统评论回复表-添加")
    //@RequiresPermissions("org.mat.ipaas.sys.biz.modules.demo:sys_comment:add")
    @PostMapping(value = "/add")
    public MatApiResponse<String> add(@RequestBody SysCommentDTO sysCommentDTO) {
        SysComment sysComment = toSysComment(sysCommentDTO);

        sysCommentService.save(sysComment);
        return MatApiResponse.success("添加成功！");
    }

    /**
     * 编辑
     *
     * @param sysCommentDTO
     * @return
     */
    //@AutoLog(value = "系统评论回复表-编辑")
    @ApiOperation(value = "系统评论回复表-编辑", notes = "系统评论回复表-编辑")
    //@RequiresPermissions("org.mat.ipaas.sys.biz.modules.demo:sys_comment:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public MatApiResponse<String> edit(@RequestBody SysCommentDTO sysCommentDTO) {
        SysComment sysComment = toSysComment(sysCommentDTO);
        sysCommentService.updateById(sysComment);
        return MatApiResponse.success("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "系统评论回复表-通过id删除")
    @ApiOperation(value = "系统评论回复表-通过id删除", notes = "系统评论回复表-通过id删除")
    //@RequiresPermissions("org.mat.ipaas.sys.biz.modules.demo:sys_comment:delete")
    @DeleteMapping(value = "/delete")
    public MatApiResponse<String> delete(@RequestParam(name = "id", required = true) String id) {
        sysCommentService.removeById(id);
        return MatApiResponse.success("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    //@AutoLog(value = "系统评论回复表-批量删除")
    @ApiOperation(value = "系统评论回复表-批量删除", notes = "系统评论回复表-批量删除")
    //@RequiresPermissions("org.mat.ipaas.sys.biz.modules.demo:sys_comment:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public MatApiResponse<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.sysCommentService.removeByIds(Arrays.asList(ids.split(",")));
        return MatApiResponse.success("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "系统评论回复表-通过id查询")
    @ApiOperation(value = "系统评论回复表-通过id查询", notes = "系统评论回复表-通过id查询")
    @GetMapping(value = "/queryById")
    public MatApiResponse<SysCommentDTO> queryById(@RequestParam(name = "id", required = true) String id) {
        SysComment sysComment = sysCommentService.getById(id);
        if (sysComment == null) {
            return MatApiResponse.fail("未找到对应数据");
        }
        return MatApiResponse.success(toSysCommentDTO(sysComment));
    }


    /**
     * 导出excel
     *
     * @param sysCommentDTO
     */
    //@RequiresPermissions("org.mat.ipaas.sys.biz.modules.demo:sys_comment:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(SysCommentDTO sysCommentDTO) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        SysComment sysComment = toSysComment(sysCommentDTO);
        return super.exportXls(request, sysComment, SysComment.class, "系统评论回复表");
    }

    /**
     * 通过excel导入数据
     *
     * @return
     */
    //@RequiresPermissions("sys_comment:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public MatApiResponse<?> importExcel() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        HttpServletResponse response = attributes.getResponse();

        return super.importExcel(request, response, SysComment.class);
    }


    private Page<SysCommentVODTO> toSysCommentVODTOPage(IPage<SysCommentVO> pageList) {
        Page<SysCommentVODTO> sysCommentVODTOPage = new Page<>();
        List<SysCommentVODTO> sysCommentVODTOList = new ArrayList<>();
        if (pageList != null && CollectionUtils.isNotEmpty(pageList.getRecords())) {
            for (SysCommentVO sysCommentVO : pageList.getRecords()) {
                sysCommentVODTOList.add(toSysCommentVODTO(sysCommentVO));
            }
        }

        sysCommentVODTOPage.setTotal(pageList.getTotal());
        sysCommentVODTOPage.setSize(pageList.getSize());
        sysCommentVODTOPage.setCurrent(pageList.getCurrent());
        sysCommentVODTOPage.setRecords(sysCommentVODTOList);

        return sysCommentVODTOPage;
    }

    private SysCommentVODTO toSysCommentVODTO(SysCommentVO sysCommentVO) {
        if (sysCommentVO == null) {
            return null;
        }
        SysCommentVODTO sysCommentVODTO = new SysCommentVODTO();
        sysCommentVODTO.setId(sysCommentVO.getId());
        sysCommentVODTO.setTableName(sysCommentVO.getTableName());
        sysCommentVODTO.setTableDataId(sysCommentVO.getTableDataId());
        sysCommentVODTO.setFromUserId(sysCommentVO.getFromUserId());
        sysCommentVODTO.setCommentContent(sysCommentVO.getCommentContent());
        sysCommentVODTO.setCreateTime(sysCommentVO.getCreateTime());
        sysCommentVODTO.setFileList(toSysCommentVODTOList(sysCommentVO.getFileList()));
        sysCommentVODTO.setToUserId(sysCommentVO.getToUserId());
        sysCommentVODTO.setCommentId(sysCommentVO.getCommentId());
        sysCommentVODTO.setFromUserId_dictText(sysCommentVO.getFromUserId_dictText());
        sysCommentVODTO.setToUserId_dictText(sysCommentVO.getToUserId_dictText());
        sysCommentVODTO.setFromUserAvatar(sysCommentVO.getFromUserAvatar());
        sysCommentVODTO.setToUserAvatar(sysCommentVO.getToUserAvatar());
        return sysCommentVODTO;
    }

    private List<SysCommentFileVoDTO> toSysCommentVODTOList(List<SysCommentFileVo> fileList) {
        List<SysCommentFileVoDTO> sysCommentFileVoDTOList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(fileList)) {
            for (SysCommentFileVo sysCommentFileVo : fileList) {
                sysCommentFileVoDTOList.add(toSysCommentFileVoDTO(sysCommentFileVo));
            }
        }

        return sysCommentFileVoDTOList;
    }

    private SysCommentFileVoDTO toSysCommentFileVoDTO(SysCommentFileVo sysCommentFileVo) {
        if (sysCommentFileVo == null) {
            return null;
        }
        SysCommentFileVoDTO sysCommentFileVoDTO = new SysCommentFileVoDTO();
        sysCommentFileVoDTO.setFileId(sysCommentFileVo.getFileId());
        sysCommentFileVoDTO.setSysFormFileId(sysCommentFileVo.getSysFormFileId());
        sysCommentFileVoDTO.setName(sysCommentFileVo.getName());
        sysCommentFileVoDTO.setFileSize(sysCommentFileVo.getFileSize());
        sysCommentFileVoDTO.setUrl(sysCommentFileVo.getUrl());
        sysCommentFileVoDTO.setType(sysCommentFileVo.getType());
        sysCommentFileVoDTO.setStoreType(sysCommentFileVo.getStoreType());
        return sysCommentFileVoDTO;
    }

    private SysComment toSysComment(SysCommentDTO sysCommentDTO) {
        if (sysCommentDTO == null) {
            return null;
        }
        SysComment sysComment = new SysComment();
        sysComment.setId(sysCommentDTO.getId());
        sysComment.setTableName(sysCommentDTO.getTableName());
        sysComment.setTableDataId(sysCommentDTO.getTableDataId());
        sysComment.setFromUserId(sysCommentDTO.getFromUserId());
        sysComment.setToUserId(sysCommentDTO.getToUserId());
        sysComment.setCommentId(sysCommentDTO.getCommentId());
        sysComment.setCommentContent(sysCommentDTO.getCommentContent());
        sysComment.setCreateBy(sysCommentDTO.getCreateBy());
        sysComment.setCreateTime(sysCommentDTO.getCreateTime());
        sysComment.setUpdateBy(sysCommentDTO.getUpdateBy());
        sysComment.setUpdateTime(sysCommentDTO.getUpdateTime());
        return sysComment;
    }


    private SysCommentDTO toSysCommentDTO(SysComment sysComment) {
        if (sysComment == null) {
            return null;
        }
        SysCommentDTO sysCommentDTO = new SysCommentDTO();
        sysCommentDTO.setId(sysComment.getId());
        sysCommentDTO.setTableName(sysComment.getTableName());
        sysCommentDTO.setTableDataId(sysComment.getTableDataId());
        sysCommentDTO.setFromUserId(sysComment.getFromUserId());
        sysCommentDTO.setToUserId(sysComment.getToUserId());
        sysCommentDTO.setCommentId(sysComment.getCommentId());
        sysCommentDTO.setCommentContent(sysComment.getCommentContent());
        sysCommentDTO.setCreateBy(sysComment.getCreateBy());
        sysCommentDTO.setCreateTime(sysComment.getCreateTime());
        sysCommentDTO.setUpdateBy(sysComment.getUpdateBy());
        sysCommentDTO.setUpdateTime(sysComment.getUpdateTime());
        return sysCommentDTO;
    }

    private Page<SysCommentFileVoDTO> toSysCommentFileVoDTOPage(IPage<SysCommentFileVo> pageList) {
        Page<SysCommentFileVoDTO> sysCommentFileVoDTOPage = new Page<>();
        List<SysCommentFileVoDTO> sysCommentFileVoDTOList = new ArrayList<>();
        if (pageList != null && CollectionUtils.isNotEmpty(pageList.getRecords())) {
            for (SysCommentFileVo sysCommentFileVo : pageList.getRecords()) {
                sysCommentFileVoDTOList.add(toSysCommentFileVoDTO(sysCommentFileVo));
            }
        }

        sysCommentFileVoDTOPage.setTotal(pageList.getTotal());
        sysCommentFileVoDTOPage.setSize(pageList.getSize());
        sysCommentFileVoDTOPage.setCurrent(pageList.getCurrent());
        sysCommentFileVoDTOPage.setRecords(sysCommentFileVoDTOList);

        return sysCommentFileVoDTOPage;
    }


    private Page<SysCommentDTO> tpSysCommentDTOPage(IPage<SysComment> pageList) {
        Page<SysCommentDTO> sysCommentDTOPage = new Page<>();
        List<SysCommentDTO> sysCommentDTOList = new ArrayList<>();
        if (pageList != null && CollectionUtils.isNotEmpty(pageList.getRecords())) {
            for (SysComment sysComment : pageList.getRecords()) {
                sysCommentDTOList.add(toSysCommentDTO(sysComment));
            }
        }

        sysCommentDTOPage.setTotal(pageList.getTotal());
        sysCommentDTOPage.setSize(pageList.getSize());
        sysCommentDTOPage.setCurrent(pageList.getCurrent());
        sysCommentDTOPage.setRecords(sysCommentDTOList);

        return sysCommentDTOPage;
    }

}
